/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * MegeGUI.java
 *
 * Created on 14/07/2009, 13:35:10
 */

package gui.swing;

import core.compress.zip.ThreadMerge;
import core.config.Configuration;
import core.util.FilesFilter;
import core.util.JGoogleAnalytics;
import gui.MainSystray;
import gui.factory.components.AbstractProgressableMergeGUI;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import javax.swing.JFileChooser;
import resources.Messages;

/**
 *
 * @author vinicius
 */
public class MergeGUI extends javax.swing.JPanel implements AbstractProgressableMergeGUI{

    private ThreadMerge threadMerge;
    List<File> filesToMerge = null;
    File dirOutPut = null;
    /*
     * INTERFACE
     */
    public void setMaximumProgress(long maximumProgress)
    {
        this.jProgressBar1.setMaximum((int)maximumProgress);
    }
    public void setCurrentProgress(long currentProgress)
    {
        this.jProgressBar1.setValue((int) currentProgress);
    }
    public void setButtonsStatus(boolean eneable)
    {
        this.jButtonMerge.setEnabled(eneable);
        this.jSliderPriority.setEnabled(eneable);
        this.jButtonBrowseFileIn.setEnabled(eneable);
        this.jButtonBrowseFolderOut.setEnabled(eneable);
        this.jButtonCancel.setEnabled(!eneable);
    }

    /** Creates new form MegeGUI */
    public MergeGUI() {
        initComponents();
        JGoogleAnalytics.trackAsynchronously("Merge Feature");
        jCheckBoxCheckFiles.setVisible(false);
        filesToMerge = new ArrayList<File>();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabelFileIn = new javax.swing.JLabel();
        jTextFieldFileIn = new javax.swing.JTextField();
        jButtonBrowseFileIn = new javax.swing.JButton();
        jLabelFolderOut = new javax.swing.JLabel();
        jTextFieldFolderOut = new javax.swing.JTextField();
        jButtonBrowseFolderOut = new javax.swing.JButton();
        jLabelPassword = new javax.swing.JLabel();
        jTextFieldPassword = new javax.swing.JTextField();
        jLabelPriority = new javax.swing.JLabel();
        jSliderPriority = new javax.swing.JSlider();
        jLabelProgress = new javax.swing.JLabel();
        jProgressBar1 = new javax.swing.JProgressBar();
        jButtonMerge = new javax.swing.JButton();
        jButtonCancel = new javax.swing.JButton();
        jCheckBoxCheckFiles = new javax.swing.JCheckBox();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextAreaLog = new javax.swing.JTextArea();
        jLabelLogText = new javax.swing.JLabel();

        jLabelFileIn.setText("Arquivo de Origem:");
        jLabelFileIn.setText(Messages.message.getString("splitMerge.label.fileIn"));

        jTextFieldFileIn.setEditable(false);

        jButtonBrowseFileIn.setText("Browse...");
        jButtonBrowseFileIn.setText(Messages.message.getString("geral.browse"));
        jButtonBrowseFileIn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonBrowseFileInActionPerformed(evt);
            }
        });

        jLabelFolderOut.setText("Salvar em:");
        jLabelFolderOut.setText(Messages.message.getString("splitMerge.label.folderOut"));

        jTextFieldFolderOut.setEditable(false);

        jButtonBrowseFolderOut.setText("Browse...");
        jButtonBrowseFolderOut.setText(Messages.message.getString("geral.browse"));
        jButtonBrowseFolderOut.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonBrowseFolderOutActionPerformed(evt);
            }
        });

        jLabelPassword.setText("Senha (opcional):");
        jLabelPassword.setText(Messages.message.getString("geral.password"));

        jTextFieldPassword.setText("www.p2mbrasil.com");

        jLabelPriority.setText("Prioridade:");
        jLabelPriority.setText(Messages.message.getString("geral.priority"));

        jSliderPriority.setMaximum(3);
        jSliderPriority.setMinimum(1);
        jSliderPriority.setPaintLabels(true);
        jSliderPriority.setPaintTicks(true);
        jSliderPriority.setSnapToTicks(true);
        jSliderPriority.setValue(2);
        java.util.Hashtable<Integer, javax.swing.JLabel> table = new java.util.Hashtable<Integer, javax.swing.JLabel>();
        table.put(new Integer(1),new javax.swing.JLabel(Messages.message.getString("geral.low")));
        table.put(new Integer(2),new javax.swing.JLabel(Messages.message.getString("geral.normal")));
        table.put(new Integer(3),new javax.swing.JLabel(Messages.message.getString("geral.high")));
        jSliderPriority.setLabelTable(table);

        jLabelProgress.setText("Progresso:");
        jLabelProgress.setText(Messages.message.getString("geral.progress"));

        jProgressBar1.setStringPainted(true);

        jButtonMerge.setText("Unir");
        jButtonMerge.setText(Messages.message.getString("splitMerge.button.merge"));
        jButtonMerge.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonMergeActionPerformed(evt);
            }
        });

        jButtonCancel.setText("Cancelar");
        jButtonCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonCancelActionPerformed(evt);
            }
        });

        jCheckBoxCheckFiles.setText("Verificar erros");

        jTextAreaLog.setColumns(20);
        jTextAreaLog.setRows(5);
        jScrollPane1.setViewportView(jTextAreaLog);

        jLabelLogText.setText("Log");

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 580, Short.MAX_VALUE)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(jLabelFileIn)
                            .add(jLabelFolderOut)
                            .add(jLabelPassword)
                            .add(jLabelPriority)
                            .add(jLabelProgress))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(layout.createSequentialGroup()
                                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                    .add(org.jdesktop.layout.GroupLayout.TRAILING, jSliderPriority, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 396, Short.MAX_VALUE)
                                    .add(jTextFieldPassword, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 396, Short.MAX_VALUE)
                                    .add(jTextFieldFolderOut, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 396, Short.MAX_VALUE)
                                    .add(jTextFieldFileIn, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 396, Short.MAX_VALUE))
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                                    .add(jButtonBrowseFileIn)
                                    .add(jButtonBrowseFolderOut)))
                            .add(jProgressBar1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 483, Short.MAX_VALUE)
                            .add(layout.createSequentialGroup()
                                .add(jButtonMerge)
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                                .add(jCheckBoxCheckFiles)
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 254, Short.MAX_VALUE)
                                .add(jButtonCancel))))
                    .add(jLabelLogText))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jButtonBrowseFileIn)
                    .add(jTextFieldFileIn, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jLabelFileIn))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabelFolderOut)
                    .add(jButtonBrowseFolderOut)
                    .add(jTextFieldFolderOut, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabelPassword)
                    .add(jTextFieldPassword, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jLabelPriority)
                    .add(jSliderPriority, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .add(28, 28, 28)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jProgressBar1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jLabelProgress))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                        .add(jButtonMerge)
                        .add(jCheckBoxCheckFiles))
                    .add(jButtonCancel))
                .add(9, 9, 9)
                .add(jLabelLogText)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 114, Short.MAX_VALUE)
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonBrowseFileInActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonBrowseFileInActionPerformed
        Configuration config=Configuration.getInstance();
        JFileChooser fileChooser = new JFileChooser(config.getLastChoosenFolderMerge());
        fileChooser.setFileFilter(new FilesFilter("p2m","openp2m"));
        fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        fileChooser.setMultiSelectionEnabled(true);
        int escolha=fileChooser.showOpenDialog(this);
        if(escolha != JFileChooser.APPROVE_OPTION) {
            this.filesToMerge = null;
            return;
        }
        config.setLastChoosenFolderMerge(fileChooser.getSelectedFile().getParentFile());
        config.saveConfiguration();
        filesToMerge.clear();
        filesToMerge.addAll(Arrays.asList(fileChooser.getSelectedFiles()));
        if (this.dirOutPut == null && this.filesToMerge != null && this.filesToMerge.size() > 0)
            dirOutPut = new File(filesToMerge.get(0).getParent());
        jTextFieldFolderOut.setText(dirOutPut.getAbsolutePath());

        StringBuffer stb = new StringBuffer();
        Iterator<File> iterator = filesToMerge.iterator();
        while(iterator.hasNext()){
            File file = iterator.next();
            stb.append(file.getName());
            if(iterator.hasNext())
                stb.append(",");
        }
        jTextFieldFileIn.setText(stb.toString());
}//GEN-LAST:event_jButtonBrowseFileInActionPerformed

    private void jButtonBrowseFolderOutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonBrowseFolderOutActionPerformed
        Configuration config=Configuration.getInstance();
        JFileChooser fileChooser = new JFileChooser(config.getLastChoosenFolderMerge());
        fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        int escolha=fileChooser.showOpenDialog(this);
        if(escolha != JFileChooser.APPROVE_OPTION) {
            this.dirOutPut = null;
            return;
        }
        this.dirOutPut = fileChooser.getSelectedFile().getAbsoluteFile();
        jTextFieldFolderOut.setText(dirOutPut.getAbsolutePath());
        config.setLastChoosenFolderMerge(dirOutPut);
        config.saveConfiguration();
}//GEN-LAST:event_jButtonBrowseFolderOutActionPerformed

    private void jButtonMergeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonMergeActionPerformed
        jTextAreaLog.setText("");
        if (filesToMerge == null || filesToMerge.size() == 0) {
            MainSystray.guiFactory.getMessageDisplayer().displayErrorMessage(Messages.exception.getString("listaArquivosGUI.escolhaArquivo"));
            return;
        }
        this.setButtonsStatus(false);

        String password=jTextFieldPassword.getText();
        if (password.length()==0)
            password=null;
        else {
            if (password.length()!=password.trim().length())
                MainSystray.guiFactory.getMessageDisplayer().displayWarningMessage(Messages.exception.getString("encryptPassword.spaceAtBeginningOrEnd"));
        }

        threadMerge= new ThreadMerge(filesToMerge , this.dirOutPut , password, this);
        if (jSliderPriority.getValue()==1)
            threadMerge.setPriority(Thread.MIN_PRIORITY);
        else if (jSliderPriority.getValue()==2)
            threadMerge.setPriority(Thread.NORM_PRIORITY);
        else if (jSliderPriority.getValue()==3)
            threadMerge.setPriority(Thread.MAX_PRIORITY);
        threadMerge.start();
}//GEN-LAST:event_jButtonMergeActionPerformed

    private void jButtonCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCancelActionPerformed
        if (threadMerge!=null)
            threadMerge.keepAlive=false;
}//GEN-LAST:event_jButtonCancelActionPerformed

    public void showLog(String txt) {
        txt = txt.replace("\n", "\n\n");
        txt += "\n";
        jTextAreaLog.append(txt);
    }


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonBrowseFileIn;
    private javax.swing.JButton jButtonBrowseFolderOut;
    private javax.swing.JButton jButtonCancel;
    private javax.swing.JButton jButtonMerge;
    private javax.swing.JCheckBox jCheckBoxCheckFiles;
    private javax.swing.JLabel jLabelFileIn;
    private javax.swing.JLabel jLabelFolderOut;
    private javax.swing.JLabel jLabelLogText;
    private javax.swing.JLabel jLabelPassword;
    private javax.swing.JLabel jLabelPriority;
    private javax.swing.JLabel jLabelProgress;
    private javax.swing.JProgressBar jProgressBar1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSlider jSliderPriority;
    private javax.swing.JTextArea jTextAreaLog;
    private javax.swing.JTextField jTextFieldFileIn;
    private javax.swing.JTextField jTextFieldFolderOut;
    private javax.swing.JTextField jTextFieldPassword;
    // End of variables declaration//GEN-END:variables

    @Override
    public int getProgress() {
        return jProgressBar1.getValue();
    }


}
